package com.hzyl.famousreader.view.activity;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import cn.pedant.SweetAlert.SweetAlertDialog;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.*;
import com.umeng.analytics.MobclickAgent;
import com.hzyl.famousreader.Constant;
import com.hzyl.famousreader.R;
import com.hzyl.famousreader.databinding.ActivityRetrieveBinding;
import com.hzyl.famousreader.repository.webservice.RetrofitClient;
import com.hzyl.famousreader.repository.webservice.api.UserService;
import com.hzyl.famousreader.repository.webservice.model.Result;
import com.hzyl.famousreader.repository.webservice.model.RetrievePassword;
import com.hzyl.famousreader.router.Router;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 找回密码
 */
@Route(path = Router.ACTIVITY_RETRIEVE_PASSWORD, name = "找回密码")
public class RetrieveActivity extends AppCompatActivity {

  private ActivityRetrieveBinding binding;

  private RetrievePassword retrievePassword;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    binding = DataBindingUtil.setContentView(this, R.layout.activity_retrieve);

    BarUtils.setStatusBarColor(this, getResources().getColor(R.color.bg_sky_blue), 0);

    retrievePassword = new RetrievePassword();
    binding.setRetrievePassword(retrievePassword);

    binding.backLogin.setOnClickListener(v -> ARouter.getInstance().build(Router.ACTIVITY_LOGIN).navigation());

    binding.recoverSendvcode.setOnClickListener(v -> {
      if(StringUtils.isTrimEmpty(retrievePassword.getPhone())) {
        new SweetAlertDialog(ActivityUtils.getTopActivity(), SweetAlertDialog.WARNING_TYPE)
          .setTitleText("请输入手机号")
          .show();
        return;
      }
      if(isMobile(retrievePassword.getPhone())) {
        new CountDownTimer(30000, 1000) {
          @Override
          public void onTick(long millisUntilFinished) {
            binding.recoverSendvcode.setEnabled(false);
            binding.recoverSendvcode.setText("已发送(" + millisUntilFinished / 1000 + ")");
          }

          @Override
          public void onFinish() {
            binding.recoverSendvcode.setEnabled(true);
            binding.recoverSendvcode.setText("重新获取");
          }
        }.start();
        UserService userService = RetrofitClient.getInstance().create(UserService.class);
        userService.isUserExit(retrievePassword.getPhone()).enqueue(new Callback<Result>() {
          @Override
          public void onResponse(Call<Result> call, Response<Result> response) {
            Result result = response.body();
            if(result != null && (result.getErrno() == 0 || result.getErrno() == 100)) {
              if(result.getErrno() == 0) {
                UserService userService = RetrofitClient.getInstance().create(UserService.class);
                userService.sendSms(retrievePassword.getPhone(), Constant.SMS_RETRIEVE_TEMPLATE).enqueue(new Callback<Result>() {
                  @Override
                  public void onResponse(Call<Result> call, Response<Result> response) {
                    Result result = response.body();
                    if (result != null && result.getErrno() == Result.SUCCESS_ERRNO) {
                      ToastUtils.showShort("获取短信验证码成功");
                    } else {
                      ToastUtils.showShort("获取短信验证码失败，请重试");
                    }
                  }

                  @Override
                  public void onFailure(Call<Result> call, Throwable t) {
                    LogUtils.d("获取短信验证码异常");
                  }
                });
              } else if (result.getErrno() == 100) {
                new SweetAlertDialog(ActivityUtils.getTopActivity(), SweetAlertDialog.WARNING_TYPE)
                  .setTitleText("用户不存在")
                  .show();
              }
            } else {
              //发生了异常
              new SweetAlertDialog(ActivityUtils.getTopActivity(), SweetAlertDialog.ERROR_TYPE)
                .setTitleText("系统发生了异常，请重试")
                .show();
            }
          }

          @Override
          public void onFailure(Call<Result> call, Throwable t) {

          }
        });
      } else {
        new SweetAlertDialog(ActivityUtils.getTopActivity(), SweetAlertDialog.WARNING_TYPE)
          .setTitleText("请输入正确的手机号")
          .show();
      }
    });

    binding.reoverPwd.setOnClickListener(v -> {
      if (StringUtils.isTrimEmpty(retrievePassword.getPhone())) {
        new SweetAlertDialog(ActivityUtils.getTopActivity(), SweetAlertDialog.WARNING_TYPE)
          .setTitleText("请输入手机号")
          .show();
        return;
      }

      if(StringUtils.isTrimEmpty(retrievePassword.getPassword())) {
        new SweetAlertDialog(ActivityUtils.getTopActivity(), SweetAlertDialog.WARNING_TYPE)
          .setTitleText("请输入密码")
          .show();
        return;
      }

      if(StringUtils.isTrimEmpty(retrievePassword.getPassword())) {
        new SweetAlertDialog(ActivityUtils.getTopActivity(), SweetAlertDialog.WARNING_TYPE)
          .setTitleText("请输入确认密码")
          .show();
        return;
      }

      if(StringUtils.isTrimEmpty(retrievePassword.getSmsCode())) {
        new SweetAlertDialog(ActivityUtils.getTopActivity(), SweetAlertDialog.WARNING_TYPE)
          .setTitleText("请输入验证码")
          .show();
        return;
      }

      if(!isMobile(retrievePassword.getPhone())) {
        new SweetAlertDialog(ActivityUtils.getTopActivity(), SweetAlertDialog.WARNING_TYPE)
          .setTitleText("请输入正确的手机号")
          .show();
        return;
      }

      if(!retrievePassword.getPassword().equals(retrievePassword.getRepassword())) {
        new SweetAlertDialog(ActivityUtils.getTopActivity(), SweetAlertDialog.WARNING_TYPE)
          .setTitleText("两次输入的密码不一致")
          .show();
        return;
      }

      UserService userService = RetrofitClient.getInstance().create(UserService.class);
      userService.modifiedPassword(retrievePassword.getPhone(), retrievePassword.getPassword(),
        retrievePassword.getRepassword(), retrievePassword.getSmsCode())
        .enqueue(new Callback<Result>() {
          @Override
          public void onResponse(Call<Result> call, Response<Result> response) {
            Result result = response.body();
            if(result != null && result.getErrno() == Result.SUCCESS_ERRNO) {
              new SweetAlertDialog(ActivityUtils.getTopActivity(), SweetAlertDialog.SUCCESS_TYPE)
                .setTitleText("成功修改密码")
                .show();
              new CountDownTimer(2000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) { }

                @Override
                public void onFinish() {
                  ARouter.getInstance().build(Router.ACTIVITY_LOGIN).navigation();
                }
              }.start();
            } else {
              new SweetAlertDialog(ActivityUtils.getTopActivity(), SweetAlertDialog.WARNING_TYPE)
                .setTitleText("修改密码失败")
                .show();
            }
          }

          @Override
          public void onFailure(Call<Result> call, Throwable t) {

          }
        });
    });
  }

  /**
   * 判断一个字符串是否为手机号
   *
   * @param mobile 手机号
   * @return
   */
  public static boolean isMobile(String mobile) {

    Pattern p = Pattern.compile("^((1[3,4,5,7,8][0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");

    Matcher m = p.matcher(mobile);

    return m.matches();

  }

  /**
   * 判断密码长度是否是大于6个字符
   *
   * @param pwd
   * @return
   */
  public static boolean isPwdLength(String pwd) {
    if (pwd.length() >= 6) {
      return true;
    } else {
      return false;
    }
  }

  @Override
  protected void onPause() {
    super.onPause();
    MobclickAgent.onPageEnd("找回密码");
    MobclickAgent.onPause(this);
  }

  @Override
  protected void onResume() {
    super.onResume();
    MobclickAgent.onPageStart("找回密码");
    MobclickAgent.onResume(this);
  }
}
